package com.yz.lzq.liwushuo.http;

import android.util.Log;

import com.yz.lzq.liwushuo.config.UrlConfig;
import com.yz.lzq.liwushuo.utils.FileManger;

import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class HttpUtils {

    private static final String TAG = "=====NET===>";
    private static volatile HttpUtils singleton;

    private IApi iApi;
    private Retrofit retrofit;

    private HttpUtils() {
        init();
    }

    public static HttpUtils getInstance() {
        if (singleton == null) {
            synchronized (HttpUtils.class) {
                if (singleton == null) {
                    singleton = new HttpUtils();
                }
            }
        }
        return singleton;
    }

    private void init() {
        retrofit = new Retrofit.Builder()
                .baseUrl(UrlConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client())
                .build();

    }

    public IApi getIApi() {
        if (iApi == null)
            iApi = retrofit.create(IApi.class);
        return iApi;
    }


    private OkHttpClient client() {

        HttpLoggingInterceptor loggingInterceptor = new
                HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i(TAG, message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        final Cache cache = new Cache(FileManger.getHttpCache(), 20 * 1024 * 1024);

        OkHttpClient client = new OkHttpClient.Builder()
                .cache(cache)
                .readTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                //拦截器    拦截请求
                .addInterceptor(loggingInterceptor)
                .addNetworkInterceptor(loggingInterceptor)
                .build();
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        Request request = chain.request();
//
//                        //执行请求
//                        Response response = chain.proceed(request);
//                        return response;
//                    }
//                })


        return client;
    }
}